//
//  CZcellTableViewController.swift
//  GZWeibo666
//
//  Created by apple on 15/12/1.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

class CZcellTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "微博详情"
        
        view.backgroundColor = UIColor.whiteColor()
        
        prepareTableView()
        tableView.estimatedRowHeight = 300
    }
    private func prepareTableView() {
        view.addSubview(tableView)
        view.addSubview(bottomview)
        loaddata(0,max: 0)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        tableView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : tableView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[tb]-44-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : tableView]))
        
       bottomview.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: view, size: CGSizeMake(view.bounds.width, 44))
        
        pinglunview.addSubview(plbutton)
        pinglunview.addSubview(label)
        label.ff_AlignHorizontal(type: ff_AlignType.CenterRight, referView: plbutton, size: nil,offset: CGPoint(x: 8, y: 0))
        plbutton.ff_AlignInner(type: ff_AlignType.CenterLeft, referView: pinglunview, size: nil,offset: CGPoint(x: 13, y: 0))
       
        
        // 设置数据源和代理
        tableView.dataSource = self
        tableView.delegate = self
        bottomview.zdalegate = self
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusReuseIdentifier.NormalCell.rawValue)
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusReuseIdentifier.ForwardCell.rawValue)
        tableView.registerClass(DetailCommentCell.self, forCellReuseIdentifier: "aa")
         tableView.registerClass(CZDetailNoDataCell.self, forCellReuseIdentifier: "ss")
        //上拉刷新数据
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loaddata(0, max: self.yszs?.last?.id ?? 0)
        }
//        tableView.tableFooterView = UIView()
    }
    private func loaddata(since:Int,max:Int)
    {
        YSZComment.loadComment(status!.id,since_id: since,max_id: max ?? 0,finished: { (var comment, error) -> () in
            if comment != nil && comment?.count > 0 {
               
                // 将新获取到的数据拼接在现有数据的前面
                if since == 0
                {
                    for elment in comment!
                    {
                        self.yszs?.append(elment)
                    }
                }
                if since != 0 && max == 0
                {
                    for elment in self.yszs!
                    {
                        comment?.append(elment)
                    }
                    self.yszs = comment
                }
            }
            self.tableView.infiniteScrollingView.stopAnimating()
            self.tableView.reloadData()
           self.label.text = String(self.yszs!.count)
        })
    }
    var status: CZStatus?
    var yszs:[YSZComment]? = [YSZComment]()
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        else
        {
            if yszs?.count == 0 {
                return 1
            } else {
                // 返回 评论数量
                return yszs?.count ?? 0
            }
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if(indexPath.section==0)
        {
            if(status!.cellId()=="NormalCell")
            {
                let cell = tableView.dequeueReusableCellWithIdentifier(status!.cellId()) as! CZStatusCell
                cell.status = status
                return cell
            }
            else
            {
                let cell = tableView.dequeueReusableCellWithIdentifier(status!.cellId()) as! CZStatusForwardCell
                cell.delegate = self
                cell.status = status
                return cell
            }

        }
        else
        {
            if yszs?.count == 0
            {
                let cell = tableView.dequeueReusableCellWithIdentifier("ss") as! CZDetailNoDataCell
                cell.message = "还没有人评论"
                return cell
            }
            else
            {
                let cell = tableView.dequeueReusableCellWithIdentifier("aa") as! DetailCommentCell
                cell.model = yszs![indexPath.row]
                
                return cell
            }
        }
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        if(indexPath.section==0)
        {
            if status!.rowHeight != nil
            {
                return status!.rowHeight!
            }
            let cell = tableView.dequeueReusableCellWithIdentifier(status!.cellId()) as! CZStatusCell
            let rowHeight = cell.rowHeight(status!)
            status!.rowHeight = rowHeight
            return rowHeight
        }
        else
        {
           return UITableViewAutomaticDimension
        }
    }
    
    // 每组头部内容
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            return nil
        }
        
     return pinglunview
    }
    
    // 每组头部高度
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0
        }
        
        return 44
    }
    
    func clickcelltableview(let weiboid:CZStatus)
    {
        let table=CZcellTableViewController()
        table.status=weiboid
         table.hidesBottomBarWhenPushed = true
        YSZComment.loadComment(status!.id,since_id: 0,max_id: yszs?.last?.id ?? 0,finished: { (comment, error) -> () in
            self.yszs = comment
            self.tableView.reloadData()
        })
        navigationController?.pushViewController(table, animated: true)
    }
    
    // MARK: - 懒加载
    /// tableView
     lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Plain)
        
        return tableView
    }()
    private lazy var bottomview: CZStatusBottomView = CZStatusBottomView(frame: CGRectZero)
    private lazy var pinglunview: UIView = {
    let pinglunveiw=UIView(frame: CGRectZero)
        pinglunveiw.backgroundColor=UIColor.grayColor()
        pinglunveiw.alpha=0.5
        return pinglunveiw
    }()
    private lazy var plbutton:UIButton = {
    let button=UIButton()
        button.setTitle("评论", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        button.sizeToFit()
        button.addTarget(self, action: "click", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    private lazy var label :UILabel={
    let label=UILabel()
        label.font=UIFont.systemFontOfSize(13)
        label.sizeToFit()
        return label
    }()
    func click()
    {
        loaddata(yszs?.first?.id ?? 0,max: 0)
    }
    
}

extension CZcellTableViewController : ForwardCelldelagate,czzhuanfadalagete, YSZCommentViewControllerdelagte {
    func bgclik(weiboid:CZStatus) {
        clickcelltableview(weiboid)
    }
    func reflash() {
        plbutton.sendActionsForControlEvents(UIControlEvents.TouchUpInside)
    }
    func zhunafaclick() {
        let ysz = YSZCommentViewController(commentType: YSZCommentViewControllerType.transmit, statu: status!)
        ysz.delagate=self
        presentViewController(UINavigationController(rootViewController: ysz), animated: true, completion: nil)
    }
    func pinglunclick() {
        let ysz = YSZCommentViewController(commentType: YSZCommentViewControllerType.comments, statu: status!)
        ysz.delagate=self
        presentViewController(UINavigationController(rootViewController: ysz), animated: true, completion: nil)
    }
}
